package com.heima.user;

import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.xml.ws.spi.http.HttpHandler;
import java.util.HashMap;
import java.util.Map;

public class YongyouAiDemo {


    @Test
    public void idCardCheck2() {
        Map map = idCardOcr("https://hmtt122.oss-cn-shanghai.aliyuncs.com/demo_idcard.png");
        System.out.println(map);

    }
    @Test
    public void test(){
        Boolean check = idCardCheck("411123199701179559", "胡安宁");
        System.out.println(check);
    }

    private Map idCardOcr(String idCardUrl) {
        try {
            Map map = new HashMap<>();
            map.put("image", idCardUrl);
            map.put("imageType", "URL");
            map.put("ocrType", "0");

            Map req = executePostReq("d75c2f5794db4f4b805c1749aa75696b", map, "https://api.yonyoucloud.com/apis/dst/IdcardOCR/IdcardOCR");
            return req;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }


    private Boolean idCardCheck(String idNumber, String userName) {
        try {
            Map map = new HashMap<>();
            map.put("idNumber", idNumber);
            map.put("userName", userName);
            Map req = executePostReq("6034a919556447059912ab29e584f3d7", map, "https://api.yonyoucloud.com/apis/dst/matchIdentity/matchIdentity");
            return (Boolean) req.get("success");
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }
    }

    /**
     * 基础请求post请求
     *
     * @param apicode 用友密钥
     * @param params  请求参数 map
     * @param url     要调用接口路径
     * @return
     */
    private Map executePostReq(String apicode, Map params, String url) {
        //1.创建restTemplate客户端
        RestTemplate restTemplate = new RestTemplate();

        //2. 封装请求头信息 apicode  contentType
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("apicode", apicode);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

      /*  //3. 封装请求参数 map   idNumber   userName
        Map map = new HashMap<>();
        map.put("idNumber","411123199701179559");
        map.put("userName","胡安宁");*/
        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(params), httpHeaders);

        //4.发起请求调用 得到返回结果
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        //5.将返回结果封为map
        String body = responseEntity.getBody();
        Map map1 = JSON.parseObject(body, Map.class);
        return map1;
    }
}
